<template>
  <div class="pdf-wrapper" v-loading="loading" >
<!--    <div class="controls">-->

<!--      <el-button type="primary" size="small" @click="zoomIn">放大</el-button>-->
<!--      <el-button type="primary" size="small" @click="zoomOut">缩小</el-button>-->
<!--      <el-button style="margin-left: 10px" type="primary" size="small" @click="downloadPDF">下载</el-button>-->
<!--    </div>-->
    <div ref="pdfContainer" class="pdf-container" @mousedown="onMouseDown">
      <!-- PDF canvas will be appended here -->
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted ,watch} from "vue";
import * as pdfjsLib from "pdfjs-dist";
// 兼容版本
// import * as workerSrc from "pdfjs-dist/legacy/build/pdf.worker.min?url";
// // 原版代码
import * as workerSrc from "pdfjs-dist/build/pdf.worker.min?url";
import { PDFDocument } from "pdf-lib";

const props = defineProps(["src",'name','currentPage']);

// 配置 PDF.js worker 的路径
pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc.default;
const CMAP_URL = "/cmaps/";
const CMAP_PACKED = true;
const loading = ref(true)

const pdfContainer = ref(null);
const pdfUrl = ref("");
const pdfName = ref("");


let pdfDoc = null;
let scale = ref(1.0);
let currentPage = ref(1);
let total = ref(0);
let isDragging = ref(false);
let startX = ref(0);
let startY = ref(0);
let scrollLeft = ref(0);
let scrollTop = ref(0);
const scaleFactor = 1.1;

// watch 监听
watch(currentPage, () => {
  handleCurrentChange(currentPage.value)
});

onMounted(async () => {
  pdfUrl.value = props.src;
  pdfName.value = props.name
  currentPage.value = props.currentPage
  const loadingTask = pdfjsLib.getDocument({
    url: pdfUrl.value,
    cMapUrl: CMAP_URL,
    cMapPacked: CMAP_PACKED,
  });
  // const loadingTask = pdfjsLib.getDocument(pdfUrl.value);
  pdfDoc = await loadingTask.promise;
  total.value = pdfDoc.numPages;
  console.log('pdftotal',total.value)
  loading.value = false
  renderPage(currentPage.value);
  pdfContainer.value.addEventListener('wheel', function(event) {
    event.preventDefault(); // 阻止默认的滚动行为

    if (event.deltaY < 0) {
      // 向前滚动，放大
      scale.value *= scaleFactor;
    } else {
      // 向后滚动，缩小
      scale.value /= scaleFactor;
    }
    renderPage(currentPage.value);
  }, { passive: false }); // 注意：在某些浏览器中，需要设置为{ passive: false }以允许默认行为
});
// let finalText = '';
const renderPage = async (num) => {
  const page = await pdfDoc.getPage(num);
  // const textContent = await page.getTextContent()
  // if(textContent.items.length){
  //   finalText += `${textContent.items.map(item => item.str).join(' ')}\n`;
  // }
  // console.log(finalText)
  const viewport = page.getViewport({ scale: scale.value });
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");
  canvas.height = viewport.height;
  canvas.width = viewport.width;

  const renderContext = {
    canvasContext: context,
    viewport: viewport,
  };
  await page.render(renderContext).promise;
  pdfContainer.value.innerHTML = "";
  pdfContainer.value.appendChild(canvas);
};

const handleCurrentChange = (page) => {
  currentPage.value =page
  renderPage(currentPage.value);
}

const zoomIn = () => {
  scale.value += 0.1;
  renderPage(currentPage.value);
};

const zoomOut = () => {
  if (scale.value > 0.2) {
    scale.value -= 0.1;
    renderPage(currentPage.value);
  }
};

const nextPage = () => {
  if (currentPage.value < total.value) {
    currentPage.value += 1;
    renderPage(currentPage.value);
  }
};

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value -= 1;
    renderPage(currentPage.value);
  }
};

const downloadPDF = async () => {
  const existingPdfBytes = await fetch(pdfUrl.value).then((res) =>
    res.arrayBuffer()
  );
  const pdfDoc = await PDFDocument.load(existingPdfBytes);
  const pdfBytes = await pdfDoc.save();
  const blob = new Blob([pdfBytes], { type: "application/pdf" });
  const link = document.createElement("a");
  link.href = window.URL.createObjectURL(blob);
  link.download = "downloaded.pdf";
  link.click();
};

const onMouseDown = (e) => {
  isDragging.value = true;
  startX.value = e.pageX - pdfContainer.value.offsetLeft;
  startY.value = e.pageY - pdfContainer.value.offsetTop;
  scrollLeft.value = pdfContainer.value.scrollLeft;
  scrollTop.value = pdfContainer.value.scrollTop;
  document.addEventListener("mousemove", onMouseMove);
  document.addEventListener("mouseup", onMouseUp);
};

const onMouseMove = (e) => {
  if (!isDragging.value) return;
  const x = e.pageX - pdfContainer.value.offsetLeft;
  const y = e.pageY - pdfContainer.value.offsetTop;
  const walkX = x - startX.value;
  const walkY = y - startY.value;
  pdfContainer.value.scrollLeft = scrollLeft.value - walkX;
  pdfContainer.value.scrollTop = scrollTop.value - walkY;
};

const onMouseUp = () => {
  isDragging.value = false;
  document.removeEventListener("mousemove", onMouseMove);
  document.removeEventListener("mouseup", onMouseUp);
};
</script>

<style scoped>
.pdf-wrapper {
  width: 100%;
  /*height: 100vh;*/
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.pdf-container {
  width: 100%;
  height: calc( 100vh - 80px);
  display: flex;
  justify-content: space-evenly;
  align-items: baseline;
  overflow: auto;
  cursor: grab;
}

.pdf-container:active {
  cursor: grabbing;
}

/*.controls {*/
/*  margin-top: 10px;*/
/*  display: flex;*/
/*  justify-content: center;*/
/*  margin-bottom: 10px;*/
/*}*/
.pdf-page{
  width: 100%;
  position: fixed;
  bottom: 10px;
  left: 10px;
}

</style>
